package com.example.books2.controller;

import com.example.books2.entity.Book;
import com.example.books2.entity.BorrowRecord;
import com.example.books2.entity.BackupRecord;
import com.example.books2.service.LibraryService;
import jakarta.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import java.nio.file.Path;
import java.nio.file.Paths;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/library")
public class LibraryController {
    @Autowired
    private LibraryService libraryService;
    
    @Autowired
    private EntityManager entityManager;
    
    @Value("${backup.dir:backup}")
    private String backupDir;
    
    @PostMapping("/borrow")
    public ResponseEntity<Boolean> borrowBook(
            @RequestParam Long bookId,
            @RequestParam Long userId) {
        boolean success = libraryService.borrowBook(bookId, userId);
        return ResponseEntity.ok(success);
    }
    
    @PostMapping("/return/{borrowRecordId}")
    public ResponseEntity<Void> returnBook(@PathVariable Long borrowRecordId) {
        libraryService.returnBook(borrowRecordId);
        return ResponseEntity.ok().build();
    }
    
    @PostMapping("/backup")
    public ResponseEntity<String> backupDatabase(@RequestParam String description) {
        String fileName = libraryService.backupDatabase(description);
        return ResponseEntity.ok(fileName);
    }
    
    @PostMapping("/restore")
    public ResponseEntity<Void> restoreDatabase(@RequestParam Long backupId) {
        libraryService.restoreDatabase(backupId);
        return ResponseEntity.ok().build();
    }
    
    @GetMapping("/books")
    public List<Book> getAllBooks() {
        return libraryService.getAllBooks();
    }
    
    @GetMapping("/records")
    public List<BorrowRecord> getBorrowRecords() {
        return libraryService.getBorrowRecords();
    }
    
    @GetMapping("/backups")
    public List<BackupRecord> getBackupRecords() {
        return libraryService.getBackupRecords();
    }
    
    @GetMapping("/backup/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadBackup(@PathVariable String fileName) {
        try {
            Path path = Paths.get(backupDir, fileName);
            Resource resource = new UrlResource(path.toUri());
            
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                    .body(resource);
            } else {
                throw new RuntimeException("备份文件不存在或无法读取");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("下载备份文件失败: " + e.getMessage(), e);
        }
    }
} 